const koa = require("koa");
const router = require("koa-router")();
const koaBody = require('koa-body');

const fs = require("fs");
const path = require("path");

const static = require("koa-static");

const app = new koa();

router.post("/file", async ctx => {
    // console.log(ctx.request.files.logo.path);    //此处logo是因为form表单里提交的name为logo
    var file = ctx.request.files.logo.path;
    var baseName = path.basename(file);
    /** 1.创建一个可读流 */
    var reader = fs.createReadStream(file);
    /** 2.设置上传图片的文件名 */
    var upFilePath = `./static/${baseName}`;
    /** 3.创建一个可写流 */
    var writer = fs.createWriteStream(upFilePath);
    /** 4.可读流通过管道写入可写流 */
    reader.pipe(writer);
    ctx.body = "上传成功"
})

app.use(static(path.join(__dirname,"static")));
/**
 * 此处的app.use(koaBody({}))必须要写在app.use(router.routes())的上面，
 * 否则上面获取到的文件会显示undefined
 */
app.use(koaBody({
    multipart: true,
    formidable: {
        maxFieldsSize: 200 * 1024 * 1024,
        keepExtensions: true
    }
}))
app.use(router.routes())

app.listen(5000)
